# To change this template, choose Tools | Templates
# and open the template in the editor.

require 'matrix'

class Markov
  def initialize(n, mat)
    @mat = mat
    @n = n
    @masta = Array.new
    @prob = Array.new(10)
    table_reference(n)
  end

  def table_reference(n)
    beg = ?a
    @ref = Array.new(n.to_i)
    n.to_i.times do |i|
      @ref[i] = beg.chr
      beg = beg.to_i() + 1
    end
  end

  def find_top(index)
    @ref.length.times do |i|
      if i == index
        return @ref[i]
      end
    end
    return false
  end

  def convert_top_to_index(top)
    @ref.length.times do |i|
      if @ref[i] == top
        return i
      end
    end
    return false
  end

  def next_point(point)
     row = Array.new
     index = 0
     @mat.row(point) { |item| row.push(item.to_f) }
     row.length.times do |i|
       if row[i] > 0
        #puts "row #{@ref[i]}"
         p = row[i] * 10
         p.to_i.times do |j|
          @prob[index + j] = @ref[i]
         end
         index += p
      end
     end
     event = rand(10)
     #puts @prob.inspect
     return @prob[event]
  end

  def go_through
      point = rand(@n.to_i())
      print find_top(point).to_s + " "
      20.times do
        point = next_point(point)
        print "#{point} "
        point = convert_top_to_index(point)
      end
      puts ''
  end

  def conex(i)
    res = Array.new

    while i < @mat.row_size
      @flag = 0
      put_conex(res, i)
      if @flag == 0
        i +=1
      elsif @flag == 1
        i = 0
      end
    end
    res = res.sort
    res = res.uniq
    print "Composante connexe : "
    res.each { |x| print x, " " }
    @masta += res
    @masta = @masta.sort
    puts
  end

  def conex_full
    i = 0
    
    if @masta.length < @mat.row_size
      while i < @mat.row_size
        conex(i) if @masta[i] != find_top(i) && @masta.length < @mat.row_size
        i +=1
      end
    end
  end

  def put_conex(res, i)
    res.push(find_top(i)) if res.empty?
    if res.include?(find_top(i))
      j = 0
      while j < @mat.row_size
        if @mat[i, j] > 0 && !res.include?(find_top(j))
          res.push(find_top(j))
          @flag = 1
        end
        j +=1
      end
    end
  end

end
